package genstream

/**
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: 12.4.11
 * Time: 12:31
 * To change this template use File | Settings | File Templates.
 */

class ListStreamIterator(private[this] var holders: List[InputStreamHolder], closeHandler: () => Unit = null) extends InputStreamIterator {

  private[this] var toBeClosed: List[InputStreamHolder] = Nil

  def next() = {
    closeHolders

    if (holders.isEmpty)
      null
    else {
      val nextHolder = holders.head
      toBeClosed ::= nextHolder
      holders = holders.tail

      nextHolder
    }
  }

  private def closeHolders() {
    toBeClosed.foreach(_.getInputStream.close)
    toBeClosed = Nil
  }

  def close() = {
    closeHolders
    if (closeHandler != null) closeHandler()
  }

}